package com.vercon.commonmirror.network;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;


/**
 * Subscriber基类,可以在这里处理client网络连接状况
 * （比如没有wifi，没有4g，没有联网等）
 * Created by fcn-mq on 2017/4/19.
 */

public abstract class MyObserve<T> implements Observer<T> {

    /*private Context context;

    public MySubscriber(Context context) {
        this.context = context;
    }*/


    public abstract void onNetError(Throwable e);


    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable e) {

        //  Log.e("tag","MySubscriber.throwable ="+e.toString());
        //  Log.e("tag","MySubscriber.throwable ="+e.getMessage());
//        EventBus.getDefault().post(new NoNetEvent());
        NetErrorException error = null;
        if (e != null) {
            // 对不是自定义抛出的错误进行解析
            if (!(e instanceof NetErrorException)) {
                if (e instanceof UnknownHostException) {
                    error = new NetErrorException(e, NetErrorException.NoConnectError);
                } else if (e instanceof JSONException || e instanceof JsonParseException) {
                    error = new NetErrorException(e, NetErrorException.PARSE_ERROR);
                } else if (e instanceof SocketTimeoutException) {
                    error = new NetErrorException(e, NetErrorException.SocketTimeoutError);
                } else if (e instanceof ConnectException) {
                    error = new NetErrorException(e, NetErrorException.ConnectExceptionError);
                } else {
                    error = new NetErrorException(e, NetErrorException.OTHER);
                }
            } else {
                error = new NetErrorException(e.getMessage(), NetErrorException.OTHER);
            }
        }

        // 回调抽象方法
        onNetError(error);

    }


}
